
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////Author: Shahab.Alishahian@gmail.com SA	
///////////////Target:The following methods are here for managing the action in html forms in client side.
///////////////Version:1.1
///////////////CopyRight: 2014 Noranj Co.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


	function goNext() {
	    $('#jbbox' + document.getElementById("stepvalue").value).animate({ 'top': '-500px' }, 500);
	    $('#stepvalue').val(parseInt($('#stepvalue').val()) + 1);
	    $('#overlay').fadeIn('fast', function () {
	        $('#jbbox' + ($('#stepvalue').val())).animate({ 'top': '160px' }, 500);
	    });
	}
//*************************************************************************************************************

	function closeBox() {
		$('#jbbox' + document.getElementById("stepvalue").value).animate({ 'top': '-500px' }, 500, function () {
	        $('#overlay').fadeOut('fast');
	    });
	}

//*************************************************************************************************************

	function loggedin() {
	    FB.getLoginStatus(function (response) {
	        if (response.status === 'connected') {
	            FB.api('/me', function (user) {
	                if (!($("#fbid").val()) && ($("#jbUserName").val())) {
	                    alert('Authentication Failed!');
	                }
	                else {
	                    $("#fbid").val(user.id);
	                    $("#jbFirstName").val(user.first_name);
	                    $("#jbLastName").val(user.last_name);
	                    $("#jbUserName").val(user.email);
	                    $("#jbEmailAddress").val(user.email);
	                    getFriends();
	                }
	            });
	        }
	    });
	}
   
//*************************************************************************************************************
	function addFriendtoUser(data){
		 var request = gapi.client.jb.user.insert({
			 'address':data.address,
			 'age':data.age,
			 'city':data.city,
			 'country':data.country,
			 'dateCreated':data.dateCreated,
			 'email':data.email,
			 'facebookId':data.facebookId,
			 'firstName':data.firstName,
			 'lastName':data.lastName,
			 'gender':data.gender,
			 'ipAddress':data.ipAddress,
			 'merchantId':data.gender,
			 'friendIds':data.friendIds
			 });
			 request.execute(function(jsonResp, rawResp) {
				  return jsonResp.id;
		     });
	}
	
//*************************************************************************************************************	
	//By selecting each friends from facebook friend list, we automatically add that facebook user into user entity.
	function addUser(){
		var userFriendsData; 
    	if($.cookie("friendList")=="null") 
    		return; 
    	
    	var contacts0 = JSON.parse($.cookie("friendList")).data;
    	
    	//Read the friendList and friendListNotAllowed, and added to an array and made it ready for inserting to datastore. 
		var friendIds = [];
		for (var i = 0; i < contacts0.length; i++) {
			 friendIds.push(contacts0[i].id);
		}
		
		if($.cookie("friendListNotAllowed")!="null"){ 
    		var contacts1 = JSON.parse($.cookie("friendListNotAllowed")).data;
    		for (var i = 0; i < contacts1.length; i++) {
    			friendIds.push(contacts1[i].id);
    		}
    		 userFriendsData = $.merge(contacts0, contacts1);
		}
		else{
			 userFriendsData =contacts0 ;
		}
		
		FB.api('/me', function (user) {
            if (!($("#fbid").val()) && ($("#jbUserName").val())) {
                alert('Authentication Failed!');
            }
            else {
            	var tempdata = {};
       		 	tempdata['address'] = '0';
    			tempdata['age'] = '0';
    			tempdata['city'] = '0';
    			tempdata['country'] = '0';
    			tempdata['dateCreated'] = returnToday();
    			tempdata['email'] = user.email;
    			tempdata['facebookId'] = user.id;
    			tempdata['firstName'] = user.first_name;
    			tempdata['gender'] = '0';
    			tempdata['lastName'] = user.last_name;
    			tempdata['merchantId'] = $("#jbMerchantId").val();
    			setAddUser(tempdata,friendIds); //this method source file is server.js
            }
		});
	}
//*************************************************************************************************************
    //function to load friends
    function loadFriends() {
        //get array of friends
        FB.api('/me/friends', function (response) {
            //console.log(response);
            var divContainer = $('#facebookFriendList');
            for (i = 0; i < response.data.length; i++) {
                $(document.createElement("div")).attr({ id: 'facebookFriendListItem' + i, class: 'facebookimages' }).appendTo(divContainer);
                $(document.createElement("img")).attr({ src: 'https://graph.facebook.com/' + response.data[i].id + '/picture', title: response.data[i].name, onClick: 'selectFriend(' + response.data[i].id + ',"' + response.data[i].name +',"' + response.data[i].username + '");' }).appendTo(document.getElementById('facebookFriendListItem' + i));
            }
        });
    }

    function getFriends(){
      var theword = '/me/friends';
      var divInfo = document.getElementById("facebookFriendList");
      FB.api(theword, function(response) {
        var friends = response.data;
        for (var i = 0; i < friends.length; i++) {
        	getFriend(friends[i].id,i,friends.length);
         }
        });
      }
      
    function getFriend(friendid,index,lenght){
    	var divInfo = document.getElementById("facebookFriendListUl");
    	var divList = divInfo.innerHTML;
    	FB.api('/' + friendid, function (user) {
	     	if (typeof user.username!='undefined'){
	     	  divList += '<li onclick="selectFriend('+ user.id +',\'' + user.name +'\',\'' + user.username +'\');" class="friendlist" Style="background-clip:content-box;background-image:url(https://graph.facebook.com/'+ user.id +'/picture?type=square)">' ;
	     	  divList += '<div style="width:95px;padding:5px;"><a class="hlText" href="#/' + user.id +'">' + user.name.toLowerCase() + '</a></div></li>';
	     	  
	       	}
	     	$(divList).appendTo(document.getElementById("facebookFriendListUl"));
	    });
    }
    
    function filterFriend(header, list){
       
      input = $("#txtSearchFriends");
      $("#txtSearchFriends")
        .change( function () {
          var filter = $(this).val();
         
          if(filter) {
            $("#facebookFriendListUl").find("a:not(:Contains(" + filter + "))").parent().parent().fadeOut();
            $("#facebookFriendListUl").find("a:Contains(" + filter + ")").parent().parent().fadeIn();
          } else {
            $("#facebookFriendListUl").find("li").fadeIn();
          }
          return false;
        })
      .keyup( function () {
          // fire the above change event after every letter
          $(this).change();
      });
     
    }

//*************************************************************************************************************

    function selectFriend(id,name,username) {
    	var date = new Date();
    	date.setTime(date.getTime() + (60 * 1000))
        var divContainer = $('#selectedFriends');
        divContainer.append('<div class="uiToken ' + id + '">' + name +  '&nbsp<span onclick="$(\'.' + id + '\').remove();removeItem(\'' + id + '\');" class="uiToken">X</span>' + '</div>');
       var jsonFriendList = {};
       var tempdata = {
			"data" : [{"id":id,"name":name,"username":username}]
        };
       
       if($.cookie("friendList") == 'null'){
        	$.cookie("friendList", JSON.stringify(tempdata),date);
        }
        else{
        	 jsonFriendList = JSON.parse($.cookie("friendList"));
             jsonFriendList.data.push(tempdata.data[0]);
             $.cookie("friendList", JSON.stringify(jsonFriendList),date);
        }
       addFriend(id,name,username);
    }

//*************************************************************************************************************
    function sendSelectedFreind() {
        var divContainer = $('#selectedFriends');
         $('.finalSelectedFriends').each(function(){
        	 $(this).append(divContainer.html());
        });
    }

//*************************************************************************************************************
    //Removing userId from cookie object which keeping a list of selected friends
    function removeItem(id){
    	var date = new Date();
    	date.setTime(date.getTime() + (60 * 1000))
    	var friendList = JSON.parse($.cookie("friendList"));
    	var friendListNotAllowed = JSON.parse($.cookie("friendListNotAllowed"));
    	var contributorsList = JSON.parse($.cookie("contributorsList")); 
    	
    	if($.cookie("friendList") != 'null')
    	{
	    	for(var i = 0; i < friendList.data.length; i++)
	    	{
	    	  if(friendList.data[i].id == id)
	    	  {
	    	   // delete  friendList.data[i] ;
	    		friendList.data.splice(i,1);
	    	  }
	    	}
	    	$.cookie("friendList",null);
	    	$.cookie("friendList", JSON.stringify(friendList),date);
    	}
    	if($.cookie("friendListNotAllowed") != 'null')
		{
	    	for(var i = 0; i < friendListNotAllowed.data.length; i++)
	    	{
	    	  if(friendListNotAllowed.data[i].id == id)
	    	  {
	    	    //delete  friendListNotAllowed.data[i] ;
	    		 friendListNotAllowed.data.splice(i,1);
	    	  }
	    	}
	    	$.cookie("friendListNotAllowed",null);
	    	$.cookie("friendListNotAllowed", JSON.stringify(friendListNotAllowed),date);
		}
		
		if($.cookie("contributorsList") != 'null')
		{
	    	for(var i = 0; i < contributorsList.data.length; i++)
	    	{
	    	  if(contributorsList.data[i].fbid == id)
	    	  {
	    		 contributorsList.data.splice(i,1);
	    	  }
	    	}
	    	$.cookie("contributorsList",null);
	    	$.cookie("contributorsList", JSON.stringify(contributorsList),date);
		}
    }
    
    
  //*************************************************************************************************************
   
  //*************************************************************************************************************
    //SA:To insert the board information into board entity at server side.
    function saveBoard(){
    	
    	var userFriendsData; 
    	if($.cookie("friendList")=="null") 
    		return; 
    	
    	var contacts0 = JSON.parse($.cookie("contributorsList")).data;
    	
    	//Read the friendList and friendListNotAllowed, and added to an array and made it ready for inserting to datastore. 
		var friendIds = [];
		for (var i = 0; i < contacts0.length; i++) {
			 friendIds.push(contacts0[i].id);
		}
		
		
		//Create boardItem object
		var boardItemData = {};
		boardItemData['description'] =  returnToday();
		boardItemData['imageURL'] = $("#jbImageUrl").val();
		boardItemData['title'] = 'Poll your friend about' ;
		boardItemData['merchantId'] =  $("#jbMerchantId").val();
		boardItemData['url'] = $("#jbMessageLink").val();
		boardItemData['uniqueId'] = 0;

		//Create board object and add the boardItem to it.
	    var boardData = {};
		boardData['boardDescription'] = $("#jbMessageLink").val();
		boardData['boardItem'] = boardItemData;
		boardData['boardKeywords'] = '[meta-Keywords]';
		boardData['boardName'] = 'NA';
		boardData['boardTitile'] = '[meta-Title]';;
		boardData['dateCreated'] = returnToday();
		boardData['friendIds'] = friendIds; //Remove duplicate values
		boardData['merchantId'] = $("#jbMerchantId").val();
		boardData['userId'] = $("#jbUserId").val();
		
		//Create boardItemDiscussion object.
		var boardItemDiscussionData = {};
		boardItemDiscussionData['boardItemId'] =$("#jbBoardId").val();
		boardItemDiscussionData['date'] =  returnToday();
		boardItemDiscussionData['discussion'] = $("#conversationText").val();
		boardItemDiscussionData['faceBookReference'] = 'NA';
		boardItemDiscussionData['userId'] = $("#jbUserId").val();
				
		addBoard(boardData,boardItemDiscussionData);  
		delete boardData;
		delete boardItemDiscussionData;
		delete contacts0;
		delete contacts1;
    }
    

//*************************************************************************************************************
    function returnToday(){
    	  var today = new Date();
          var dd = today.getDate();
          var mm = today.getMonth()+1;
          var yyyy = today.getFullYear();
          
          if(dd<10){dd='0'+dd;} 
          if(mm<10){mm='0'+mm;}
          
          var returnToday = yyyy + '' + mm +'' + dd ;
          delete yyyy;
          delete mm;
          delete dd;
          return returnToday;
    }
//*************************************************************************************************************
//Koodecaf APIs part.
//*************************************************************************************************************

//*************************************************************************************************************
    //TODO:SA:Please correct the IDs in below
      function sendApprequests() {
    	  console.log(appId);
  	    	var  arr = [];
  	    	var list = JSON.parse($.cookie("friendListNotAllowed")).data ;
  	    	if (list.length > 0 ){
  		    	for ( i = 0; i < list.length; i++) {
  		    	    arr.push(list[i].id);
  		    	}
  		     
  	           FB.getLoginStatus(function (response) {
  					FB.ui({
  							app_id: appId,
  							method: 'apprequests',
  							message: "Please accept the invitation.",
  							picture: $('#imageUrl').val(),
  							title: 'JingleBoard',
  							to: arr,
  							}, function(response) {
  							    if(response && response.hasOwnProperty('to')) {
  							for(i = 0; i < response.to.length; i++) {
  							    console.log("" + i + " ID: " + response.to[i]);
  							    }
  							}
  							else  {
  								 console.log('No ');
  							}
  	            	});
  	           });
  	    	}
      }

//*************************************************************************************************************
     
    function sendNotifications(contacts){
	   	 for (var i = 0; i < contacts.length; i++) {
	   		 sendANotification(contacts[i].id,$("#fbid").val());
	   	 }
   		if($.cookie("friendListNotAllowed") != 'null'){
   			sendApprequests();
   		}
    }
      
    function sendANotification(contactId,senderId) {
         //var param = 'https://apps.facebook.com/'+ $('#appId').val()+'/fb_source=myapps' ;
         var param = '' ;
         var strUrl = 'https://graph.facebook.com/'+ contactId +'/notifications?access_token=' + appAccessToken + '&href=' + param + '&template= @['+senderId+'] needs to have your idea!'
         console.log(strUrl );
         FB.getLoginStatus(function (response) {
           $.ajax({ type: 'POST',
               url:strUrl,
               async: false,
               success: function (response) {
                   console.log(response);
               },
               error: function(error) {
               	var date = new Date();
               	date.setTime(date.getTime() + (60 * 1000));
               	if(error.status=='403' || error.status=='200'){
               		var tempdata = {
                   			"data" : [{"id":contactId}]
                           };
   	            	if($.cookie("friendListNotAllowed") == 'null'){
   	                	$.cookie("friendListNotAllowed", JSON.stringify(tempdata),date);
   	                }
   	                else{
   	                	 jsonFriendList = JSON.parse($.cookie("friendListNotAllowed"));
   	                     jsonFriendList.data.push(tempdata.data[0]);
   	                     $.cookie("friendListNotAllowed", JSON.stringify(jsonFriendList),date);
   	                }
               	}
               }
           });
         });
       }
          
  //*************************************************************************************************************
    function getQueryStringParams(sParam) {
        var sPageURL = window.location.search.substring(1);
        var sURLVariables = sPageURL.split('&');
        for (var i = 0; i < sURLVariables.length; i++) {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] == sParam) {
                return sParameterName[1];
            }
        }
      }

  //*************************************************************************************************************    
    function ArrayNoDupes(array) {
        var temp = {};
        for (var i = 0; i < array.length; i++)
            temp[array[i].value] = true;
        var r = [];
        for (var k in temp)
            r.push(k);
        return r;
    }